/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package apus.servlet;

import apus.action.Action;
import apus.action.ActionManager;
import apus.action.DefaultAction;
import apus.action.ActionResult;
import apus.action.AdministrationAction;
import apus.action.CashierAccSearchAction;
import apus.action.CashierSearchAction;
import apus.action.LanguageChangeAction;
import apus.action.PaidAction;
import apus.action.PasswordChangeAction;
import apus.action.PasswordSaveAction;
import apus.action.ViewLoginPageAction;
import apus.action.ViewMainPageAction;
import apus.action.account.AccountCreateAction;
import apus.action.account.AccountCreateMonthly;
import apus.action.account.AccountDeleteAction;
import apus.action.account.AccountEditAction;
import apus.action.account.AccountListAction;
import apus.action.account.AccountSaveAction;
import apus.action.account.AccountSearchAction;
import apus.action.call.CallListAction;
import apus.action.organization.OrganizationAction;
import apus.action.organization.OrganizationCreateAction;
import apus.action.organization.OrganizationDeleteAction;
import apus.action.organization.OrganizationEditAction;
import apus.action.organization.OrganizationListAction;
import apus.action.organization.OrganizationSaveAction;
import apus.action.organization.OrganizationSearchAction;
import apus.action.person.PersonAction;
import apus.action.person.PersonCreateAction;
import apus.action.person.PersonDeleteAction;
import apus.action.person.PersonEditAction;
import apus.action.person.PersonListAction;
import apus.action.person.PersonSaveAction;
import apus.action.person.PersonSearchAction;
import apus.action.phonenumber.PhoneNumberAction;
import apus.action.phonenumber.PhoneNumberCreateAction;
import apus.action.phonenumber.PhoneNumberDeleteAction;
import apus.action.phonenumber.PhoneNumberEditAction;
import apus.action.phonenumber.PhoneNumberListAction;
import apus.action.phonenumber.PhoneNumberSaveAction;
import apus.action.phonenumber.PhoneNumberSearchAction;
import apus.action.user.UserAddAction;
import apus.action.user.UserDeleteAction;
import apus.action.user.UserSaveAction;
import apus.authorisation.UserAuthorisation;
import apus.entity.User;
import apus.persistence.AccountDAO;
import apus.persistence.CallDAO;
import apus.persistence.DaoFactory;
import apus.persistence.OrganizationDAO;
import apus.persistence.PeriodDAO;
import apus.persistence.PersonDAO;
import apus.persistence.PhoneNumberDAO;
import apus.persistence.UserDAO;
import apus.persistence.jdbc.JdbcDAOFactory;
import apus.services.ServiceLocator;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author 21vek
 */
public class MainServlet extends HttpServlet {

    private ActionManager actionManager;
    private static String USER_AUTH = "userAuth";

    @Override
    public void init() throws ServletException {

        DaoFactory daoFactory = new JdbcDAOFactory();
        ServiceLocator.registerService(AccountDAO.class, daoFactory.getAccountDAO());
        ServiceLocator.registerService(CallDAO.class, daoFactory.getCallDAO());
        ServiceLocator.registerService(PersonDAO.class, daoFactory.getPersonDAO());
        ServiceLocator.registerService(OrganizationDAO.class, daoFactory.getOrganizationDAO());
        ServiceLocator.registerService(PeriodDAO.class, daoFactory.getPeriodDAO());
        ServiceLocator.registerService(PhoneNumberDAO.class, daoFactory.getPhoneNumberDAO());
        ServiceLocator.registerService(UserDAO.class, daoFactory.getUserDAO());

        actionManager = new ActionManager();
        actionManager.addAction(new PersonListAction());
        actionManager.addAction(new PersonAction());
        actionManager.addAction(new PersonCreateAction());
        actionManager.addAction(new PersonDeleteAction());
        actionManager.addAction(new PersonEditAction());
        actionManager.addAction(new PersonSaveAction());
        actionManager.addAction(new PersonSearchAction());
        actionManager.addAction(new OrganizationAction());
        actionManager.addAction(new OrganizationCreateAction());
        actionManager.addAction(new OrganizationDeleteAction());
        actionManager.addAction(new OrganizationEditAction());
        actionManager.addAction(new OrganizationListAction());
        actionManager.addAction(new OrganizationSaveAction());
        actionManager.addAction(new OrganizationSearchAction());
        actionManager.addAction(new CallListAction());
        actionManager.addAction(new AccountCreateAction());
        actionManager.addAction(new AccountDeleteAction());
        actionManager.addAction(new AccountEditAction());
        actionManager.addAction(new AccountListAction());
        actionManager.addAction(new AccountSaveAction());
        actionManager.addAction(new AccountSearchAction());
        actionManager.addAction(new AccountCreateMonthly());
        actionManager.addAction(new PhoneNumberCreateAction());
        actionManager.addAction(new PhoneNumberDeleteAction());
        actionManager.addAction(new PhoneNumberEditAction());
        actionManager.addAction(new PhoneNumberListAction());
        actionManager.addAction(new PhoneNumberSaveAction());
        actionManager.addAction(new PhoneNumberSearchAction());
        actionManager.addAction(new PhoneNumberAction());
        actionManager.addAction(new ViewMainPageAction());
        actionManager.addAction(new ViewLoginPageAction());
        
        actionManager.addAction(new CashierSearchAction());
        actionManager.addAction(new CashierAccSearchAction());
        actionManager.addAction(new PaidAction());
        
        actionManager.addAction(new AdministrationAction());
        actionManager.addAction(new UserAddAction());
        actionManager.addAction(new UserSaveAction());
        actionManager.addAction(new UserDeleteAction());
        
        actionManager.addAction(new PasswordChangeAction());
        actionManager.addAction(new PasswordSaveAction());
        
        actionManager.addAction(new LanguageChangeAction());

        actionManager.addAction(new DefaultAction());
    }

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        
        if (request.getSession().getAttribute("lang")==null){
            request.getSession().setAttribute("lang", "en");
        }

        String actionName = request.getParameter("action");
        boolean loginAction = false;

        if (actionName == null) {
            actionName = "default.action";
        }

        if (actionName.equals("login.view")) {
            loginAction = true;
        }

        if ((request.getSession().getAttribute(USER_AUTH) != null) || loginAction) {
            User user = new User();

            if (!loginAction) {
                user.setLogin(((UserAuthorisation) request.getSession().getAttribute(USER_AUTH)).getLogin());
            }

            if (ServiceLocator.getService(UserDAO.class).isActionAllowed(user, actionName) || loginAction) {

                Action action = actionManager.findAction(actionName);
                if (action == null) {
                    action = actionManager.findAction("default.action");
                }

                ActionResult forward;
                try {
                    forward = action.execute(request, response);

                    if (forward.isForward()) {
                        RequestDispatcher requestDispatcher = getServletContext()
                                .getRequestDispatcher(forward.getViewJsp());
                        requestDispatcher.forward(request, response);
                    }

                    if (forward.isRedirect()) {
                        response.sendRedirect(request.getContextPath() + "/main?action=" + forward.getAction());
                    }
                } catch (Exception e) {
                    RequestDispatcher requestDispatcher = getServletContext()
                            .getRequestDispatcher("/WEB-INF/View/error.jsp");
                    requestDispatcher.forward(request, response);
                }
            } else {
                RequestDispatcher requestDispatcher = getServletContext()
                        .getRequestDispatcher("/WEB-INF/View/accessDeniedPage.jsp");
                requestDispatcher.forward(request, response);
            }

        } else {
            response.sendRedirect(request.getContextPath() + "/main?action=login.view");
        }
    }
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
